var app = require("./app"),
    gulp = require('gulp'),
    pug = require("gulp-pug"),
    replace = require("gulp-replace"),
    plumber = require("gulp-plumber"),
    clean = require("gulp-clean"),
    path = require("path"),
    del = require("del");

Array.prototype.contains = function(obj) {
    for (var i = 0; i < this.length; i++) {
        if (obj === this[i]) {
            return true;
        }
    }
    return false;
};

//编译静态文件
function compileStatic(file) {
    return gulp.src(file, {
        base: 'src'
    }).pipe(plumber()).pipe(gulp.dest('dist'));
}

//编译pug模板
function compilePug(file) {
    return gulp.src(file, {
        base: 'src'
    }).pipe(plumber()).pipe(pug({
        pretty: true
    })).pipe(replace(/\$\{relativePath\}\//g, function(match, p1) {
        // console.log(this.file.relative);
        var relative = this.file.relative.replace(/\\/g, "/");
        return relative.substr(0, relative.lastIndexOf("/") + 1).replace(/[^\/]+/g, "..");
    })).pipe(gulp.dest("dist"));
}

//同步静态资源
gulp.task("static", ["clean"], function() {
    return compileStatic('src/static/**/*.*');
});

//编译pug模板
gulp.task("pug", ["clean"], function() {
    return compilePug("src/view/**/*.pug");
});

//监听文件变动将编译pug模板和同步静态资源
gulp.task("watch", ["clean"], function() {
    gulp.watch("src/**/*", function(event) {
        var path = event.path.replace(__dirname, "").substr(1);
        var compile = path.indexOf("view") != -1 ? compilePug : compileStatic;

        // console.log(path);

        if (app.commonFiles.contains(path)) {
            compilePug("src/view/**/*.pug");
            compileStatic('src/static/**/*.*');
        }

        if ("deleted" != event.type && path.indexOf(".") > 0) {
            compile(path);
        }

        if ("deleted" == event.type) {
            del(["dist" + path.substr(3)]);
        }
    });
});

//清楚dist目录
gulp.task("clean", function() {
    return del(['./dist']);
});

//默认
gulp.task("default", ["clean", "pug", "static", "watch"]);